import {
  DocumentEvents,
  DocumentObject,
  parameterObjectExprToId,
  parameterObjectExprToLabel,
  ParameterObjectType,
  Types,
  useCommandManager,
} from '@amcax/base';
import { docMgr, userEvents } from '@app-base/module';
import { Button, Input } from 'antd';
import { forwardRef, useEffect, useState } from 'react';
import { getUnitForExpression } from './utils';

type ExpressionDialogProps = {
  value: string;
  onChange: (val: string) => void;
  type: ParameterObjectType;
  onClose: VoidFunction;
};

export const ExpressionDialog = forwardRef<
  HTMLDivElement,
  ExpressionDialogProps
>(({ value, onChange, onClose, type }, ref) => {
  const [inputValue, setInputValue] = useState(value ?? '');

  useEffect(() => {
    setInputValue(parameterObjectExprToLabel(value, docMgr));
  }, [value]);

  const { currentCmdProps } = useCommandManager();

  const currentEditDxid = (currentCmdProps as any)?.dxid;

  const onObjectSelected = (selectedObject: DocumentObject) => {
    if (selectedObject.dxid === currentEditDxid) {
      return;
    }

    if (selectedObject.type === Types.PARAMETER_OBJECT) {
      const label = `\`${selectedObject.fullPath.replace(/^.*?\//, '')}\``;
      setInputValue((old) => (old === '' ? label : `${old} ${label}`));
    }
  };

  useEffect(() => {
    userEvents.on(DocumentEvents.SELECT_TREE_OBJECT, onObjectSelected);

    return () => {
      userEvents.off(DocumentEvents.SELECT_TREE_OBJECT, onObjectSelected);
    };
  }, []);

  const displayUnit = getUnitForExpression(type);

  return (
    <div
      ref={ref}
      className={`fixed rounded-lg z-[1000] p-4 bg-white expr-input-dialog`}
    >
      <div className='flex gap-2 items-center'>
        <Input
          className='w-[200px]'
          value={inputValue}
          autoFocus
          style={{ border: '1px solid #d9d9d9' }}
          onChange={(e) => setInputValue(e.target.value)}
        />
        {displayUnit && <div className='text-sm'>{displayUnit.name}</div>}
      </div>
      <div className='flex justify-end gap-2 pt-2'>
        <Button onClick={onClose}>取消</Button>
        <Button
          type='primary'
          onClick={() => {
            onChange?.(parameterObjectExprToId(inputValue, docMgr));
          }}
        >
          确认
        </Button>
      </div>
    </div>
  );
});
